package com.franklin.icharm;

import java.io.IOException;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.ArrayAdapter;

public class SelectEmailDialog
{
	private static final String DBG_TAG = "SelectEmailDialog";
	private static final String ACCOUNT_TYPE_GOOGLE = "com.google";
	private static final String[] FEATURES_MAIL = {"service_mail"};

	private Context mContext;
	private Callback mListener;
	private static Account[] mAccounts = null;
	private static UserConfig mUserConfig;

	protected SelectEmailDialog(Context context, Callback listener)
	{
		mContext = context;
		mListener = listener;
		mUserConfig = new UserConfig(mContext);

		// Get the account list
		AccountManager.get(context).getAccountsByTypeAndFeatures(ACCOUNT_TYPE_GOOGLE, FEATURES_MAIL,
			new AccountManagerCallback<Account[]>()
			{
				@Override
				public void run(AccountManagerFuture<Account[]> future)
				{
					try
					{
						mAccounts = future.getResult();
					} catch (OperationCanceledException oce)
					{
						Log.e(DBG_TAG, "Got OperationCanceledException", oce);
					} catch (IOException ioe)
					{
						Log.e(DBG_TAG, "Got OperationCanceledException", ioe);
					} catch (AuthenticatorException ae)
					{
						Log.e(DBG_TAG, "Got OperationCanceledException", ae);
					} // try-catch
					showDialog();
				} // run
			}, null);
	} // Constructor

	private void showDialog()
	{	// Build the dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setIcon(R.drawable.ic_launcher);
        builder.setTitle(R.string.select_one_name);
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(mContext, android.R.layout.select_dialog_singlechoice);
        String selectedEmail = mUserConfig.getConfString(UserConfig.KV_USER_EMAIL, null);
        int selectedItem = -1;
		for (int i = 0; i < mAccounts.length; i++)
		{
			String email = mAccounts[i].name;
			arrayAdapter.add(email);
			if (selectedEmail != null && email.equals(selectedEmail))
				selectedItem = i;
		} // for
        builder.setNegativeButton(R.string.cancel, mListener);
        builder.setSingleChoiceItems(arrayAdapter, selectedItem, mListener);
        builder.show();
        mListener.onShow(mAccounts);
	} // showDialog

	public interface Callback extends DialogInterface.OnClickListener
	{
		public void onShow(Account[] accounts);
	} // Callback
} // SelectEmailDialog
